# 参考https://blog.csdn.net/qq_15994257/article/details/119852292?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164255924016781685375985%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=164255924016781685375985&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-14-119852292.pc_search_result_cache&utm_term=Python+%E5%AD%A6%E7%94%9F%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F%E3%80%90%E5%AD%97%E5%85%B8%E7%BB%93%E6%9E%84%E7%89%88%E3%80%91%E6%BA%90%E7%A0%81%E5%88%86%E4%BA%AB&spm=1018.2226.3001.4187


# 在v2.0的基础上再优化下，看着漂亮多了

import os

class Student:
    def __init__(self,_name='',_age=0,_tel=''):
        self.name = _name
        self.age = _age
        self.tel = _tel
        self.stu_dict = {'name':self.name,'age':self.age,'tel':self.tel}

class System:
    def __init__(self):
        self.user_list = []

    @staticmethod
    def show_menu():
        print('-' * 20)
        print('= 1.  添加学生')
        print('= 2.  删除学生')
        print('= 3.  修改学生')
        print('= 4.  查询全部学生')
        print('= 5.  查询某个学生')
        print('= 6.  保存信息')
        print('= 7.  退出系统')
        print('-' * 20)

    def add_stu(self):
        """添加学生"""
        name = input('请输入要添加学生的姓名:')
        # 如果学生姓名重复则重新输入
        while True:
            for each in self.user_list:
                if name == each.name:
                    print('该学生已存在')
                    name = input('请重新输入:')
                    break
            else:
                break
        age = int(input('请输入学生年龄:'))
        tel = input('请输入学生电话:')
        self.user_list.append(Student(name,age,tel))
        print('添加成功')

    def del_stu(self):
        """删除学生信息"""
        name = input('请输入要删除的学生姓名:')
        # 循环判断学生是否存在
        for i, each in enumerate(self.user_list):
            if each.name == name:
                self.user_list.pop(i)
                print('删除成功')
                break
        else:
            print('查无此人！')

    def update_stu(self):
        """修改某个学生"""
        name = input('请输入要修改的学生姓名:')
        for i,each in enumerate(self.user_list):
            if each.name == name:
                # 使用while True 保证修改后的学生不重复
                while True:
                    name = input('请输入修改后的姓名:')
                    for stu in self.user_list:
                        if stu.name == name:
                            print('该学生已存在，请重新输入')
                            break
                    else:
                        break
                age = int(input('输入修改后的年龄:'))
                tel = input('输入修改后的电话:')
                self.user_list[i] = Student(name,age,tel)
                print('修改成功')
                break
        else:
            print('查无此人！')

    def show_all_stu(self):
        """查询所有学生"""
        # 如果存在学生信息则打印，若没有信息则提示为空
        if self.user_list:
            print('序号\t\t\t姓名\t\t\t年龄\t\t\t电话')
            for i,each in enumerate(self.user_list):
                print(f'{i+1}\t\t\t{each.name}\t\t\t{each.age}\t\t\t{each.tel}')
        else:
            print('没有学生信息')

    def show_one_stu(self):
        """查询单个学生"""
        name = input('输入要查询的学生姓名:')
        for each in self.user_list:
            if each.name == name:
                print(f'{each.name}\t\t\t{each.age}\t\t\t{each.tel}')
                break
        else:
            print('查无此人！')

    def data_info(self):
        """载入数据"""
        # 判断文件是否存在，若不存在则退出
        if not os.path.exists('./stu_data.txt'):
            return
        # 如果存在则对数据进行提取、载入，并以实例对象的形式保存到user_list中
        with open('stu_data.txt','r') as f:
            data_list = eval(f.read())
            for each in data_list:
                self.user_list.append(Student(each['name'],each['age'],each['tel']))

    def save_data(self):
        """导出数据"""
        with open('stu_data.txt','w') as f:
            data_list = []
            # 把类对象的字典形式提取出来并转为str形式保存
            # data_list 为临时变量,临时保存列表
            for each in self.user_list:
                data_list.append(each.stu_dict)
            f.write(str(data_list))

    def start(self):
        # 在系统开始时加载数据
        self.data_info()
        # 通过死循环来保证程序不主动退出
        while True:
            System.show_menu()

            choose = input('请输入操作：')
            if choose == '1':
                self.add_stu()
            elif choose == '2':
                self.del_stu()
            elif choose == '3':
                self.update_stu()
            elif choose == '4':
                self.show_all_stu()
            elif choose == '5':
                self.show_one_stu()
            elif choose == '6':
                print('保存成功')
                self.save_data()
            # 如果退出前不保存，不会自动保存数据
            elif choose == '7':
                print('退出系统...')
                break
            else:
                print('输入错误，请重新输入...')

manager = System()
manager.start()




